<template>
  <div class="uploadStyle">
    <a-button class="addImgSaveStyle" type="primary" @click="addImgSave">确定保存</a-button>
    <a-row>
      <!-- v-if="fileList.length < 9" -->
      <a-col v-show="fileList.length < 9" :xl="{ span: 6 }" :xxl="{ span: 6 }" :lg="{ span: 8 }" :sm="{ span: 8 }" :xs="{ span: 8 }">
        <div style="margin: 0 12px">
          <a-upload-dragger
            name="files"
            list-type="text"
            :file-list="fileList"
            :multiple="multiple"
            action="/file/api/v1/site/upload/inline"
            accept=".doc, .docx, .xls, .xlsx, .pdf, .zip, .rar, .jpg, .jpeg, .png"
            @preview="handlePreview"
            @change="handleChange"
          >
            <a-icon type="cloud-upload" style="fontsize: 42px; color: #e8e8e8" />
            <p class="uploadtext">
              将文件拖动到此处，或
              <span style="color: #6a66f6">点击上传</span>
            </p>
          </a-upload-dragger>
        </div>
      </a-col>

      <a-col
        :xl="{ span: 6 }"
        :xxl="{ span: 6 }"
        :lg="{ span: 8 }"
        :sm="{ span: 8 }"
        :xs="{ span: 8 }"
        v-for="(i, index) in fileList"
        :key="index"
      >
        <div class="listBox">
          <div style="width: 100%; height: 158px; background: #fafafa; overflow: hidden">
            <div class="shadowStyleDis">
              <div
                class="shadowStyle"
                v-if="
                  (i.response && !getSrc(i.response.data[0], ['rar', 'zip'])) || (!i.response && i.src && !getSrc(i.src, ['rar', 'zip']))
                "
              >
                <div @click="handlePreview(i)">
                  <div class="shadowStyleEye">
                    <a-icon type="eye" />
                  </div>
                  <div class="shadowStyleText">预览</div>
                </div>
              </div>
              <img width="100%" style="max-height: 158px; object-fit: cover" :src="`${i.src}?token=${token}`" v-if="i.type === 'img'" />
              <img
                width="100%"
                style="max-height: 158px; object-fit: cover"
                :src="`${i.response.data[0]}?token=${token}`"
                v-else-if="i.type.substring(0, 6) === 'image/' && i.response && i.response.data.length !== 0"
              />
              <div class="widCss" v-else>
                <img width="100%" src="./img/word.png" v-if="i.response && getSrc(i.response.data[0], ['doc', 'docx'])" />
                <img width="100%" src="./img/word.png" v-else-if="i.type === 'file' && i.src && getSrc(i.src, ['doc', 'docx'])" />
                <img
                  width="100%"
                  src="./img/xls.png"
                  v-else-if="i.type.substring(0, 12) === 'application/' && getType(i.type, ['.sheet', 'vnd.ms-excel']) && i.response"
                />
                <img width="100%" src="./img/xls.png" v-else-if="i.type === 'file' && i.src && getSrc(i.src, ['xls', 'xlsx'])" />
                <img
                  width="100%"
                  src="./img/pdf.png"
                  v-else-if="i.type.substring(0, 12) === 'application/' && getType(i.type, ['pdf']) && i.response"
                />
                <img width="100%" src="./img/pdf.png" v-else-if="i.type === 'file' && i.src && getSrc(i.src, ['pdf'])" />
                <img width="100%" src="./img/rar.png" v-else-if="i.response && getType(i.type, ['', 'zip', 'x-zip-compressed'])" />
                <img width="100%" src="./img/rar.png" v-else-if="i.type === 'file' && i.src && getSrc(i.src, ['rar', 'zip'])" />
              </div>
            </div>
          </div>
          <div class="listBoxBootom">
            <a-row>
              <a-col :span="14" class="ovte">{{ i.name }}</a-col>
              <a-col :span="10" style="text-align: right">
                <a-icon @click="onDownload(i)" type="download" class="iconText" />
                <a-icon @click="ondelete(index)" type="delete" class="iconText" />
              </a-col>
            </a-row>
          </div>
        </div>
      </a-col>
    </a-row>
    <a-modal width="800px" title="查看" :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <div v-if="!iframeSrc" class="images" v-viewer="{ movable: false }">
        <h3>单击查看大图</h3>
        <img style="width: 100%" v-for="src in previewImage" :src="src" :key="src" />
      </div>
      <a-spin tip="加载中，请稍后..." :spinning="spinningval">
        <iframe width="750px" height="600px" v-if="iframeSrc" :src="iframeSrc" frameborder="0"></iframe>
      </a-spin>
    </a-modal>
    <!-- <a-upload
      action="/file/api/v1/site/upload/inline"
      list-type="picture-card"
      :file-list="fileList"
      :multiple="multiple"
      name="files"
      accept=".doc, .docx, .xls, .xlsx, .pdf, .zip, .rar, .jpg, .jpeg, .png"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < limit">
        <a-icon type="plus" />
        <div class="ant-upload-text">上传</div>
      </div>
    </a-upload>

    <div>
      <a-button type="primary" @click="addImgSave">确定保存</a-button>
    </div>-->
  </div>
</template>
<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
import "viewerjs/dist/viewer.css";
import Viewer from "v-viewer";
import Vue from "vue";
Vue.use(Viewer);

export default {
  props: {
    srcData: {
      type: String,
      default: ""
    },
    multiple: {
      // 选择时是否可以选择多个
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  watch: {
    MathNum(val) {
      if (this.fileList.length !== 0) {
        const a = JSON.parse(JSON.stringify(this.fileList));
        this.fileList = a.filter((z) => {
          if (z.response) {
            if (z.response.code !== 400) {
              return z;
            } else {
              this.$message.error("上传失败，请检查附件！");
            }
          } else {
            return z;
          }
        });
        if (this.fileList.length > 9) {
          this.fileList = this.fileList.splice(0, 9);
        }
      }
    },
    srcData: {
      handler: function (val, oldVal) {
        this.fileList = [];
        if (val && val !== "") {
          const srcData = JSON.parse(JSON.stringify(val));
          srcData.split(",").forEach((element, index) => {
            this.fileList.push({
              uid: index,
              name: element.split("/").slice(-1)[0],
              status: "done",
              type: this.imgTypes.includes(element.split("/").slice(-1)[0].split(".").splice(-1)[0]) ? "img" : "file",
              src: element,
              imgUrl: `${element}?token=${this.$store.state.auth.token}`,
              url: `${element}?token=${this.$store.state.auth.token}`
            });
          });
        }
      },
      deep: true
    }
  },
  created() {
    if (this.srcData && this.srcData !== "") {
      const srcData = JSON.parse(JSON.stringify(this.srcData));
      srcData.split(",").forEach((element, index) => {
        this.fileList.push({
          uid: index,
          name: element.split("/").slice(-1)[0],
          status: "done",
          type: this.imgTypes.includes(element.split("/").slice(-1)[0].split(".").splice(-1)[0]) ? "img" : "file",
          src: element,
          imgUrl: `${element}?token=${this.$store.state.auth.token}`,
          url: `${element}?token=${this.$store.state.auth.token}`
        });
      });
    }
  },
  data() {
    return {
      spinningval: false,
      MathNum: "",
      returnOperation: true,
      iframeSrc: "",
      token: this.$store.state.auth.token,
      previewVisible: false,
      previewImage: [],
      fileList: [],
      imgTypes: [
        "bmp",
        "jpg",
        "png",
        "tif",
        "gif",
        "pcx",
        "tga",
        "exif",
        "fpx",
        "svg",
        "psd",
        "cdr",
        "pcd",
        "dxf",
        "ufo",
        "eps",
        "ai",
        "raw",
        "WMF",
        "webp",
        "jpeg"
      ]
    };
  },
  methods: {
    getType(i, arr) {
      const val = arr.find((z) => i.indexOf(z) !== -1);
      return val !== undefined;
    },
    getSrc(src, arr) {
      const srcSHow = arr.includes(src.split("/").slice(-1)[0].split(".").splice(-1)[0]);
      return srcSHow;
    },
    ondelete(index) {
      var that = this;
      this.$confirm({
        title: "正在删除",
        content: "删除后将无法恢复，确认删除该附件吗？",
        onOk() {
          that.returnOperation = false;
          that.fileList.splice(index, 1);
          const fileList = JSON.parse(JSON.stringify(that.fileList));
          const fileListString = [];
          fileList.forEach((element, index) => {
            fileListString.push(element.src);
          });
          // that.$emit("update:srcData", fileListString.join(","));
          // that.$emit("change", fileListString.join(","));
        }
      });
    },
    onDownload(i) {
      if (i.response && i.response.data.length !== 0) {
        window.open(`${i.response.data[0]}?token=${this.$store.state.auth.token}`);
      } else if (i.src) {
        window.open(`${i.src}?token=${this.$store.state.auth.token}`);
      }
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      const that = this;
      if (!file.url && file.response) {
        file.preview = `${file.response.data[0]}?token=${this.$store.state.auth.token}`;
      }
      this.previewImage = [file.url || file.preview];
      if (file.response && file.response.data.length !== 0) {
        if (file.response.data[0].split("/").slice(-1)[0].split(".").splice(-1)[0] === "pdf") {
          window.open(`${file.response.data[0]}?token=${this.$store.state.auth.token}`);
        } else if (file.type.substring(0, 12) === "application/") {
          this.previewVisible = true;
          this.spinningval = !this.spinningval;
          this.iframeSrc = `https://view.officeapps.live.com/op/view.aspx?src=${file.response.data[0]}?token=${this.$store.state.auth.token}`;
          setTimeout(function () {
            that.spinningval = !that.spinningval;
          }, "2000");
        } else {
          this.iframeSrc = "";
          this.previewVisible = true;
        }
      } else {
        if (file.src.split("/").slice(-1)[0].split(".").splice(-1)[0] === "pdf") {
          window.open(file.src + `?token=${this.$store.state.auth.token}`);
        } else if (file.type === "file") {
          this.previewVisible = true;
          this.spinningval = !this.spinningval;
          this.iframeSrc = `https://view.officeapps.live.com/op/view.aspx?src=${file.src}?token=${this.$store.state.auth.token}`;
          setTimeout(function () {
            that.spinningval = !that.spinningval;
          }, "2000");
        } else {
          this.iframeSrc = "";
          this.previewVisible = true;
        }
      }
    },
    getReturnOperation() {
      return this.returnOperation;
    },
    addImgSave() {
      this.returnOperation = true;
      const fileListString = [];
      this.fileList.forEach((element, index) => {
        if (element.response) {
          element.src = element.response.data[0];
          element.imgUrl = `${element.response.data[0]}?token=${this.$store.state.auth.token}`;
          element.type = this.imgTypes.includes(element.name.split(".").splice(-1)[0]) ? "img" : "file";
          fileListString.push(element.src);
          // this.$set(fileList, index, element);
        } else {
          fileListString.push(element.src);
        }
      });
      this.$emit("update:srcData", fileListString.join(","));
      this.$emit("change", fileListString.join(","));
    },
    handleChange({ file, fileList }) {
      this.$nextTick(() => {
        this.fileList = [];
        this.fileList = fileList;
        this.returnOperation = false;
        this.MathNum = Math.ceil(Math.random() * 10);
      });
    }
  }
};
</script>
<style lang="scss">
.uploadStyle {
  position: relative;
  .ant-upload.ant-upload-drag {
    border: 1px solid hsl(0, 0%, 85%);
    // width: 268px;
    height: 212px;
  }
  .uploadtext {
    font-size: 14px;
    color: #666666;
    margin-top: 10px;
  }
  .ant-upload-list {
    display: none;
  }
  .ant-upload-drag {
    margin: 0 auto;
  }
}
</style>
<style scoped>
.shadowStyle {
  display: flex;
  position: absolute;
  cursor: pointer;
  display: none;
  width: 94%;
  height: 158px;
  top: 10px;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
}
.shadowStyleText {
  font-size: 14px;
  color: #ffffff;
}
.shadowStyleEye {
  width: 30px;
  height: 30px;
  background: rgba(255, 255, 255, 0.3);
  color: #ffffff;
  font-size: 18px;
  text-align: center;
  line-height: 30px;
  border-radius: 50%;
  margin-bottom: 5px;
}
.shadowStyleDis:hover .shadowStyle {
  display: flex;
}
.widCss {
  width: 50px;
  height: 62px;
  text-align: center;
  margin: 0 auto;
  margin-top: 38px;
  display: flex;
}
.fileArrBox {
  float: left;
}
.listBox {
  border-radius: 3px;
  border: 1px solid #e8e8e8;
  padding: 10px;
  position: relative;
  margin: 0 auto;
  margin-bottom: 24px;
  margin-left: 12px;
  margin-right: 12px;
}
.clearfix:after {
  /*伪元素是行内元素 正常浏览器清除浮动方法*/
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  padding: 0;
  margin: 0;
  *zoom: 1; /*ie6清除浮动的方式 *号只有IE6-IE7执行，其他浏览器不执行*/
}
.iconText {
  font-size: 18px;
  color: #9c9c9c;
  margin-left: 9px;
}
.ovte {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.listBoxBootom {
  height: 32px;
  line-height: 32px;
  padding-top: 5px;
}
.addImgSaveStyle {
  position: absolute;
  top: -82px;
  right: 29px;
}
</style>
